﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DnaCoreLib
{
    public class TaskWorkerBase : DnaCoreLib.ITaskWorker
    {
        public delegate void WorkerUpdateEventHandler(object o, WorkerStatusEventArgs workerStatusEventArgs);
        public event WorkerUpdateEventHandler OnProgressUpdate;
        public event WorkerUpdateEventHandler OnWorkComplete;

        public WorkerStatusEventArgs WorkStatus {get;set;}

        public string SystemName { get; set; }
        public int Priority { get; set; }

        public TaskWorkerBase(string systemName, int priority=999)
        {
            SystemName = systemName;
            Priority = priority;
            WorkStatus = new WorkerStatusEventArgs() { PercentComplete = 0, StatusMessage = "" };

        }

        protected void UpdateTheProgress(int percentComplete, string message)
        {
            bool notifyChange = false;
            if (percentComplete - 1 > WorkStatus.PercentComplete)
            {
                WorkStatus.PercentComplete = percentComplete;
                notifyChange = true;
            }
            if (message != WorkStatus.StatusMessage)
            {
                WorkStatus.StatusMessage = message;
            }
            if (notifyChange && OnProgressUpdate != null)
                OnProgressUpdate(this, WorkStatus);
        }

        protected void WorkComplete(string message)
        {
            WorkStatus.PercentComplete = 100;
            WorkStatus.StatusMessage = message;

            if (OnProgressUpdate != null)
                OnProgressUpdate(this, WorkStatus);
            if (OnWorkComplete != null)
                OnWorkComplete(this, WorkStatus);

        }

        public virtual void Execute(object parameters)
        {
            Startup();

            //Do work here

            Complete();
        }

        protected virtual void Startup()
        {
            //Load needed dataset here
            UpdateTheProgress(1, "Work Started");
        }

        protected virtual void Complete()
        {
            UpdateTheProgress(99, "Saving Work");
            //commit completed dataset here
            WorkComplete("Work complete");
        }

    }
}
